import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:untitled1/app/broker/modules/WebViewPage.dart';
import 'package:untitled1/app/pay/showLockInfoDialog.dart';
import 'package:untitled1/app/pay/showLockInfoDialog2.dart';
import 'package:untitled1/app/res/myColors.dart';
import 'package:untitled1/app/utils/utilHttpUrl.dart';
import 'package:untitled1/app/utils/utilRouter.dart';
import 'package:untitled1/app/utils/utilScreen.dart';
import 'package:untitled1/app/utils/utilStr.dart';
import 'package:untitled1/app/widgets/dialog/PayDialog.dart';


import '../../../../widgets/base_page/BaseStatefulPage.dart';
import '../../employer/employer_page/employer_page_dialog/CountdownTextSplit.dart';
import '../ServeDetailPage.dart';
import 'ServeListViewController.dart';

class ServeListView extends BaseStatefulPage {
  int type = 1;
  int page_index;
  ServeListView({super.key, required this.type,required this.page_index}) : super(pageName: "雇主-列表");

  @override
  BaseStatefulPageState<BaseStatefulPage> createState() => _MyListViewState();
}

class _MyListViewState extends BaseStatefulPageState<ServeListView> {
  final ServeListViewController controllerData = Get.put(ServeListViewController());
  //刷新控制器
  final RefreshController _refreshController = RefreshController(
    initialRefresh: false,
  );

  // 模拟下拉刷新
  void _onRefresh() async {
    // 模拟网络请求延时
   List<dynamic> list=await controllerData.fetchData();
    print(">]数据刷新  type1=${widget.type},list.isze=${list.length}");
      controllerData.list.clear();
     controllerData.list.addAll(list);
       controllerData.list.refresh();

   // print(">]请求数据成功 type2=${widget.type},list.isze=${ controllerData.list.length}");
    // 结束刷新
    _refreshController.refreshCompleted();
   setState(() {

   });
  }

  // 模拟上拉加载更多
  void _onLoading() async {
    List<dynamic> list=await controllerData.fetchData();
    print(">]加载更多 type1=${widget.type},list.isze=${list.length}");
    // 模拟网络请求延时
    if (list.isEmpty) {
      // 没有更多数据
      _refreshController.loadNoData();
    } else {
      controllerData.list.addAll(list);
      controllerData.list.refresh();
      _refreshController.loadComplete();
    }
    print(">]加载更多 type1=${widget.type},list.isze=${controllerData.list.length}");
    // 加载完成
    setState(() {

    });
  }

  @override
  void dispose() {
    _refreshController.dispose(); // 释放资源
    super.dispose();
  }

 @override
  void initState() {
    super.initState();
    if(widget.page_index==widget.type){
      WidgetsBinding.instance.addPostFrameCallback((_)  {
        _refreshController.requestRefresh();
      });
    }
  }

  @override
  void didUpdateWidget(covariant ServeListView oldWidget) {
    super.didUpdateWidget(oldWidget);
    print('>]didUpdateWidget type =${widget.type},,,isActive=${widget.page_index}---${widget.page_index==widget.type?'更新':'不更新'}');
    // _onRefresh();
    if(widget.page_index==widget.type){
      WidgetsBinding.instance.addPostFrameCallback((_)  {
        _refreshController.requestRefresh();
      });
    }
  }

  @override
  Widget buildPage(BuildContext context) {
    return getListView(context, widget.type);
  }

  Widget getListView(BuildContext context, int type) {
    return  Center(
      child: SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,  // 开启下拉刷新
        enablePullUp: true,  // 开启上拉加载
       onRefresh: _onRefresh,   // 下拉刷新回调
        onLoading: _onLoading,  // 上拉加载回调

        //头部样式
        header: ClassicHeader(
          refreshingText: "正在刷新...",
          idleText: "下拉可以刷新",
          completeText: "刷新完成",
          failedText: "刷新失败",
          releaseText: "松开立即刷新",
          textStyle: TextStyle(color: Colors.black87),
        ),
        // 自带经典尾部样式
        footer: ClassicFooter(
          noDataText: "没有更多数据",
          loadingText: "加载中...",
          idleText: "上拉加载更多",
          failedText: "加载失败，请重试",
        ),
        child: ListView.separated(
          itemCount: controllerData.list.length,
          // 总共显示 20 项
          scrollDirection: Axis.vertical,
          // 列表垂直滚动
          reverse: false,
          // 是否倒序，false 表示从上往下滚动
          controller: ScrollController(),
          // 控制滚动位置（非必须）
          primary: false,
          // 如果为 true，不允许同时设置 controller
          physics: const BouncingScrollPhysics(),
          // iOS 回弹效果
          shrinkWrap: false,
          // false 表示撑满父容器；嵌套场景设为 true
          // padding: const EdgeInsets.all(10),
          // 整体内边距
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          // 滚动时关闭键盘
          itemBuilder: (context, index) {
            return getListItemView(context, index);
          }, separatorBuilder: (BuildContext context, int index) {
            return Container(
              height: 10,
              color: myColors.c_FBFBFB,
            );
        },
        ),
      ),
    );
  }

  Widget getListItemView(BuildContext context, int index) {
    String btnStr='';
    if(0== widget.type){
      btnStr='锁定';
    }else{
      btnStr='查看';
    }
    return Container(
      width: MediaQuery.of(context).size.width,
      child: Column(
        children: [
          Visibility(
            visible: 2 == widget.type, // true 显示，false 隐藏
            child: Container(
              width: MediaQuery.of(context).size.width,

              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/app/zhuangtai_bg2.png'),
                  fit: BoxFit.fill,
                ),
              ),
              height: 30,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    margin: EdgeInsets.only(left: 10),
                    child: Text(
                      '代发起定金合同',
                      style: TextStyle(color: myColors.white),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(right: 10),
                    child: Row(
                      children: [
                        Text('订单还剩', style: TextStyle(color: myColors.white)),
                        CountdownTextSplit(timeStr: "23:59:59"),
                        SizedBox(width: 10),
                        CountdownTextSplit(timeStr: "8天:23:59:59"),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                margin: EdgeInsets.only(left: 10),
                child: Row(
                  children: [
                    Text(
                      '张女士｜家员母婴${widget.type}-${index}',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: myColors.c_191919,
                      ),
                    )

                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(right: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    RichText(text: TextSpan(
                      text: '12000-20000',
                      style: TextStyle(
                        color: myColors.c_B51C21,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                      children: [
                        TextSpan(text: '/时新',
                            style: TextStyle(
                              color: myColors.c_B51C21,
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                        )
                      ]
                    ))

                  ],
                ),
              ),
            ],
          ),
          SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                margin: EdgeInsets.only(left: 10),
                child: Row(
                  children: [
                    Text('内蒙古', style: TextStyle(color: myColors.c_707070)),
                    Container(
                      alignment: Alignment.center,
                      width: 20,
                      child: Text(
                        '|',
                        style: TextStyle(color: myColors.c_707070),
                      ),
                    ),
                    Text('39岁', style: TextStyle(color: myColors.c_707070)),
                    Container(
                      alignment: Alignment.center,
                      width: 20,
                      child: Text(
                        '|',
                        style: TextStyle(color: myColors.c_707070),
                      ),
                    ),
                    Text('8年以上工作经验', style: TextStyle(color: myColors.c_707070)),
                  ],
                ),
              ),

            ],
          ),
          SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                margin: EdgeInsets.only(left: 10),
                child: Row(
                  children: [
                    Text('服务999+', style: TextStyle(color: myColors.c_707070)),
                    SizedBox(width: 10),
                    Text('手脚勤快', style: TextStyle(color: myColors.c_707070)),
                    SizedBox(width: 10),
                    Text('普通话良好', style: TextStyle(color: myColors.c_707070)),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(right: 10),
                child: GestureDetector(
                  onTap: () {
                    print('>]按钮被点击了yyyyyyy');
                    if(widget.type==0){
                      PayDialog(context: context,money: '100',onConfirm: (){});
                    }else{
                      // String url=utilHttpUrl.server_details+'?token=${utilStr.generateRandomString(6)}';
                      // utilRouter.to(WebViewPage(url: url, webpageName:'雇主详情'));
                     utilRouter.to(ServeDetailPage());
                    }

                  },
                  child: Container(
                    width: 50,
                    // 按钮宽度
                    height: 20,
                    // 按钮高度
                    alignment: Alignment.center,
                    // 文字居中
                    decoration: BoxDecoration(
                      color: Colors.blue, // 按钮背景色
                      borderRadius: BorderRadius.circular(50), // 圆角
                      boxShadow: [
                        // 阴影效果（可选）
                        BoxShadow(
                          color: Colors.black.withOpacity(0.2),
                          blurRadius: 4,
                          offset: Offset(0, 2),
                        ),
                      ],
                      gradient: LinearGradient(
                        // 渐变背景（可选）
                        colors: [myColors.c_F89596, myColors.c_FF4142],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                    ),
                    child: Text(
                      '${btnStr}',
                      style: TextStyle(
                        color: Colors.white, // 字体颜色
                        fontSize: 10, // 加粗
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }


}
